package com.photoeditor.demo.util;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.common.base.ComponentContext;
import com.common.base.utils.AppUtils;
import com.photoeditor.demo.app.Global;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

/**
 * Created by @author winn on 2018/11/7.
 */

public class SignUtils {

    /**
     * 对接口添加加密参数
     * 注意：需要在所有参数都添加完后，再调用此方法
     * @param jsonObject
     */
    public static void appendSign(JSONObject jsonObject) {
        String secretKey = Global.SERVER_KEY;
        try {
            jsonObject.put("timestamp", System.currentTimeMillis());
            jsonObject.put("secretKey", secretKey);
            jsonObject.put("deviceId", ProtocolUtil.getAndroidId());
            jsonObject.put("dtype", Global.SERVER_KEY_VERSION);
            jsonObject.put("v", AppUtils.getVersionCode(ComponentContext.getContext()));

            String sign = genSign(jsonObject);
            jsonObject.put("sign", sign);
            jsonObject.remove("secretKey");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static String getSign(JSONObject jsonObject) {
        String secretKey = Global.SERVER_KEY;
        try {
            jsonObject.put("secretKey", secretKey);
            jsonObject.put("deviceId", ProtocolUtil.getAndroidId());
            jsonObject.put("dtype", Global.SERVER_KEY_VERSION);
            jsonObject.put("v", AppUtils.getVersionCode(ComponentContext.getContext()));
            return genSign(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String genSign(JSONObject jsonObject) {
        String ret = "";
        Object picData = jsonObject.opt("pic");
        if (picData != null) {
            jsonObject.remove("pic");
        }
        Iterator<String> keys = jsonObject.keys();
        ArrayList<String> list = new ArrayList<>();
        while (keys.hasNext()) {
            list.add(keys.next());
        }
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : list) {
            Object value = jsonObject.opt(key);
            stringBuilder.append(key);
            stringBuilder.append("=");
            stringBuilder.append(value);
            stringBuilder.append("&");
        }
        ret = stringBuilder.substring(0, stringBuilder.length() - 1);
        ret = md5(ret);
        if (picData != null) {
            try {
                jsonObject.put("pic", picData);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }


    @NonNull
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
